<template>
    <!-- <page-meta>
        <navigation-bar :back="false" :search="true"></navigation-bar>
    </page-meta> -->
    <view>
        <navigation-bar :back="false" :search="true"></navigation-bar>

        <view style="display: flex; padding-left: 30rpx; padding-top: 18rpx; padding-bottom: 25rpx">
            <view :class="tabIndex == 0 ? 'topTag2' : 'topTag1'" @tap="tabClick" data-data="0">分类</view>
            <view :class="tabIndex == 1 ? 'topTag2' : 'topTag1'" @tap="tabClick" data-data="1" style="padding-left: 110rpx">排行</view>
        </view>

        <view style="height: 15rpx"></view>
        <view class="t1" v-if="tabIndex == 0">
            <view class="t2">
                <view :class="tab1Index == item.category2Id ? 't33' : 't3'" @tap="changeTag1" :data-data="item.category2Id" v-for="(item, index) in slidList" :key="index">
                    {{ item.category2Name }}
                </view>
            </view>
            <scroll-view scroll-y class="scrollView" :refresher-triggered="isUp" @scrolltolower="down" refresher-enabled @refresherrefresh="up" :lower-threshold="80">
                <view class="t4">
                    <view class="t5" @tap="goToGame" :data-data="item" v-for="(item, index) in gameData" :key="index">
                        <image :src="item.logoSquare" mode="" class="t6" />

                        <view class="t7">{{ item.appname }}</view>
                    </view>
                    <view v-if="gameData.length % limit != 0" style="text-align: center; color: gray; margin-top: 30rpx; width: 100%">没有更多了</view>
                    <view style="height: 30rpx"></view>
                </view>
            </scroll-view>
        </view>

        <view class="t111" v-if="tabIndex == 1">
            <view class="t8">
                <view :class="tab2Index == 0 ? 't9' : 't10'" @tap="changeTag2" :data-data="0">人气榜</view>
                <view :class="tab2Index == 1 ? 't9' : 't10'" @tap="changeTag2" :data-data="1">畅销榜</view>
                <view :class="tab2Index == 2 ? 't9' : 't10'" @tap="changeTag2" :data-data="2">新游榜</view>
            </view>
            <scroll-view scroll-y class="scrollView" :refresher-triggered="isUp" @scrolltolower="down" refresher-enabled @refresherrefresh="up" :lower-threshold="80">
                <view class="t11" v-for="(item, index) in gameData" :key="index">
                    <view class="t12">
                        <view class="t13">
                            <image :src="item.logoSquare" mode="" class="t14" />
                        </view>
                        <view class="t15">
                            <view class="t16">{{ item.appname }}</view>
                            <view class="t17">{{ item.briefIntro }}</view>
                            <view class="t18">
                                <view class="t19">{{ item.clickCount ? item.clickCount / 16 + '万+玩过' : '0人玩过' }}</view>
                                <view class="t20"></view>
                                <view class="t19">{{ item.category2Name }}</view>
                                <view class="t20"></view>
                                <view class="t19">{{ item.category3Name }}</view>
                            </view>
                        </view>
                        <view class="t21">
                            <view class="t22" @tap="goToGame" :data-data="item">秒玩</view>
                        </view>
                    </view>

                    <view class="line"></view>
                </view>
                <view v-if="gameData.length % limit != 0" style="text-align: center; color: gray; margin-top: 30rpx; width: 100%">没有更多了</view>
                <view style="height: 30rpx"></view>
            </scroll-view>
        </view>
        <!-- 添加自定义登录提示框 -->
        <CustomConfirm
            :visible.sync="showLoginConfirm"
            title="温馨提示"
            content="亲，您还没登录，请先登录~"
            @confirm="handleLoginConfirm"
            @cancel="handleLoginCancel"
        />
    </view>
</template>

<script>
import navigationBar from '../../components/navigation-bar/navigation-bar.vue';
import CustomConfirm from '../../components/CustomConfirm/CustomConfirm.vue';
import loginStatusUtils from '../../utils/loginStatusUtils';
import { getGame, addClick, addOpen } from '../../api/getApi';
import { addMyGame } from '../../api/userGameApi';
import { updateMyViewTabBarText } from '../../utils/tabBarUtils';

export default {
    // 导入自定义组件
    components: {
        navigationBar,
        CustomConfirm
    },
    data() {
        return {
            showLoginConfirm: false,//是否显示登录提示框
            tabIndex: uni.getStorageSync('tabIndex') ? uni.getStorageSync('tabIndex') : 0,
            isUp: false,
            tab1Index: uni.getStorageSync('tab1Index') ? uni.getStorageSync('tab1Index') : 1,
            tab2Index: uni.getStorageSync('tab2Index') ? uni.getStorageSync('tab2Index') : 0,
            gameData: [],
            page: 1,
            limit: 35,

            slidList: [
                {
                    category2Name: '休闲益智',
                    category2Id: 1
                },
                {
                    category2Name: '角色扮演',
                    category2Id: 2
                },
                {
                    category2Name: '动作射击',
                    category2Id: 3
                },
                {
                    category2Name: '棋牌桌游',
                    category2Id: 5
                },
                {
                    category2Name: '竞技对战',
                    category2Id: 7
                },
                {
                    category2Name: '其他游戏',
                    category2Id: 0
                }
            ],

            myGame: ''
        };
    },

    /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {
		// 创建Promise数组来跟踪请求
		const promises = [];

		// 获取数据
		const promise = getGame({
			page: this.page,
			limit: this.limit,
			hot: this.tab2Index == 0 && this.tabIndex == 1 ? 'true' : 'false',
			openHot: this.tab2Index == 1 && this.tabIndex == 1 ? 'true' : 'false',
			category2Id: this.tabIndex == 0 ? this.tab1Index : ''
		}).then((res) => {
			const list = res.data.list;
			if (list && list.length > 0) {
				this.setData({
					gameData: list
				});
			}
		});
		promises.push(promise);
        updateMyViewTabBarText();
		// 等待所有请求完成
		Promise.all(promises).then(() => {
			// 停止下拉刷新动画
			uni.stopPullDownRefresh();
		}).catch(error => {
			console.error('刷新数据出错:', error);
			// 即使出错也要停止刷新动画
			uni.stopPullDownRefresh();
		});
	},
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        updateMyViewTabBarText();
        this.setData({
            gameData: [],
            page: 1
        });
        this.getData();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            tabIndex: uni.getStorageSync('tabIndex') ? uni.getStorageSync('tabIndex') : 0,
            tab1Index: uni.getStorageSync('tab1Index') ? uni.getStorageSync('tab1Index') : 1,
            tab2Index: uni.getStorageSync('tab2Index') ? uni.getStorageSync('tab2Index') : 0
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {

        //登录确认
        handleLoginConfirm(){
            this.showLoginConfirm = false;
            uni.navigateTo({
                url: '/pages/login/login'
            });
        },

        //登录取消
        handleLoginCancel(){
            this.showLoginConfirm = false;
        },


        tabClick(event) {
            if (event.target.dataset.data == '0') {
                this.setData({
                    tabIndex: 0
                });
                uni.setStorageSync('tabIndex', 0);
            }
            if (event.target.dataset.data == '1') {
                this.setData({
                    tabIndex: 1
                });
                uni.setStorageSync('tabIndex', 1);
            }
            this.setData({
                gameData: [],
                page: 1
            });
            this.getData();
        },

        getData() {
            getGame({
                page: this.page,
                limit: this.limit,
                hot: this.tab2Index == 0 && this.tabIndex == 1 ? 'true' : 'false',
                openHot: this.tab2Index == 1 && this.tabIndex == 1 ? 'true' : 'false',
                category2Id: this.tabIndex == 0 ? this.tab1Index : ''
            }).then((res) => {
                const list = res.data.list;
                if (list && list.length > 0) {
                    this.setData({
                        gameData: [...this.gameData, ...list]
                    });
                }
                
                // 确保在任何情况下都重置刷新状态
                if (this.isUp) {
                    this.setData({
                        isUp: false
                    });
                }
            }).catch(error => {
                console.error('获取数据出错:', error);
                // 出错时也要结束刷新状态
                if (this.isUp) {
                    this.setData({
                        isUp: false
                    });
                }
            });
        },

        //原始只跳进微信小程序的代码
       /*  goToGame(e) {
            let itemdata = e.currentTarget.dataset.data;
            if (itemdata.appid) {
                uni.navigateToMiniProgram({
                    appId: itemdata.appid,
                    path: '?wxgamepro=CpsCBgAAoXkpQY9UXS9__OwV',
                    envVersion: 'release',
                    success: (res) => {
                        let myGame = uni.getStorageSync('myGame');
                        if (!myGame) {
                            myGame = [];
                        } else {
                            myGame = JSON.parse(myGame).slice(0, 300);
                        }
                        if (!myGame.find((v) => v.id === itemdata.id)) {
                            myGame = [itemdata, ...myGame];
                        }
                        uni.setStorageSync('myGame', JSON.stringify(myGame));
                        this.setData({
                            myGame: myGame
                        });
                        addOpen({
                            id: itemdata.id
                        });
                    }
                });
                addClick({
                    id: itemdata.id
                });
            } else {
                uni.showToast({
                    title: `尊敬的大人对对不不起起！此游戏出了点小问题~`,
                    icon: 'none'
                });
            }
        }, */



        
        goToGame(e) {
            //检查登录状态
            if(!loginStatusUtils.checkLoginAndShowConfirm(this)){
                    return;
                }

			let itemdata = e.currentTarget.dataset.data;
			let loginType = 'app';

            //加入我的游戏
			addMyGame({
				kyyGameId:itemdata.id,
				kyyGameAppname:itemdata.appname,
				kyyGameLogo:itemdata.logo,
				kyyGameUrl:itemdata.gameUrl,
			}).then(res => {
				console.log('成功加入我的游戏',res);
			});

			//处于微信端时
			if (itemdata.appid && loginType === 'weixin') {
				uni.navigateToMiniProgram({
					appId: itemdata.appid,
					path: '?wxgamepro=CpsCBgAAoXkpQY9UXS9__OwV',
					envVersion: 'release',
					success: (res) => {
						let myGame = uni.getStorageSync('myGame');
						if (!myGame) {
							myGame = [];
						} else {
							myGame = JSON.parse(myGame).slice(0, 300);
						}
						if (!myGame.find((v) => v.id === itemdata.id)) {
							myGame = [itemdata, ...myGame];
						}
						uni.setStorageSync('myGame', JSON.stringify(myGame));
						this.setData({
							myGame: myGame
						});
						addOpen({
							id: itemdata.id
						});
					}
				});
				addClick({
					id: itemdata.id
				});
			}
			//处于APP端时
			else if (itemdata.userName && loginType === 'app') {

                


                //从微信小程序进入跳进，目前只能跳进首页
				/* this.sweixin.launchMiniProgram({
					id: 'gh_f03eb6ba7bc9', //要跳转小程序的原始ID
					// path: `pages/tslogin/tslogin?do=login&appName=${itemdata.username}`, //  可带参数
					// path: `https://game.weixin.qq.com/cgi-bin/comm/openlink?auth_appid=wx62d9035fd4fd2059&url=https%3A%2F%2Fgame.weixin.qq.com%2Fcgi-bin%2Fminigame%2Fstatic%2Fcps-transfer%2Findex.html%3Ft%3DAARwtQwFAAABAAAAAACb5dZ3Bq27t3udXwPJZxAAAADA8RG5WEKQmoqKviNESI_t_xpcTGNZbOvZhGLbF_si_gri_9qdvru4eA8jre-QDluA9gJxhZESxT4o%26wechat_pkgid%3Dminigame__cps_transfer_index`, //  可带参数
					success: (res) => {
						console.log('跳转成功', res);
					},
					fail: (err) => {
						console.error('跳转失败', err);
					}
				})
				 */

                 //跳进外部浏览器打开微信小游戏
				/* plus.runtime.openURL(itemdata.gameUrl, function(res) {
					console.log(res);
				}); */

				//跳进内嵌浏览器webview打开微信小游戏
				//对url进行编码
				let encodedUrl = encodeURIComponent(itemdata.gameUrl);
				addClick({
					id: itemdata.id
				});
				uni.navigateTo({
					url: `/pages/webview/webview?src=${encodedUrl}&title=${itemdata.appname}`,
				}).then(res => {
					// console.log('跳转成功', res);
					addOpen({
						id: itemdata.id
					});
				}).catch(err => {
					console.error('跳转失败', err);
				});
				
				
				
				
				
				
				
				
				
			} 

			else {
				uni.showToast({
					title: `尊敬的大人对对不不起起！此游戏出了点小问题~`,
					icon: 'none'
				});
			}
		},


        //第一个标签页tag标签
        changeTag1(e) {
            let index = e.currentTarget.dataset.data;
            this.setData({
                tab1Index: index
            });
            uni.setStorageSync('tab1Index', index);
            this.setData({
                gameData: [],
                page: 1
            });
            this.getData();
        },

        //第二个标签页tag标签
        changeTag2(e) {
            let index = e.currentTarget.dataset.data;
            this.setData({
                tab2Index: index
            });
            uni.setStorageSync('tab2Index', index);
            this.setData({
                gameData: [],
                page: 1
            });
            this.getData();
        },

        up(e) {
            this.setData({
                isUp: true,
                gameData: [],
                page: 1
            });
            
            // 获取数据
            getGame({
                page: this.page,
                limit: this.limit,
                hot: this.tab2Index == 0 && this.tabIndex == 1 ? 'true' : 'false',
                openHot: this.tab2Index == 1 && this.tabIndex == 1 ? 'true' : 'false',
                category2Id: this.tabIndex == 0 ? this.tab1Index : ''
            }).then((res) => {
                const list = res.data.list;
                if (list && list.length > 0) {
                    this.setData({
                        gameData: list
                    });
                }
                
                // 数据加载完成后，延迟一小段时间再结束刷新状态
                setTimeout(() => {
                    this.setData({
                        isUp: false
                    });
                }, 500);
            }).catch(error => {
                console.error('刷新数据出错:', error);
                // 出错时也要结束刷新状态
                this.setData({
                    isUp: false
                });
            });
        },

        down(e) {
            this.setData({
                page: this.page + 1
            });
            this.getData();
        }
    }
};
</script>
<style>
.t1 {
    display: flex;
    padding-left: 30rpx;
    height: inherit;
    overflow: hidden;
}

.t2 {
    border-right: 4rpx solid #ddd;
    display: flex;
    flex-direction: column;
    height: 100%;
}

.t3 {
    width: 142rpx;
    color: var(--GColor);
    line-height: 1;
    padding-bottom: 60rpx;
    font-size: 30rpx;
}
.t33 {
    width: 142rpx;
    color: var(--Color);
    line-height: 1;
    padding-bottom: 60rpx;
    font-size: 30rpx;
}
.t4 {
    display: flex;
    flex-wrap: wrap;
    padding: 0 15rpx 30rpx 15rpx;
    align-self: flex-start;
}

.t5 {
    width: 25%;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 210rpx;
}

.t6 {
    width: 105rpx;
    height: 105rpx;
    border-radius: 20rpx;
}

.t7 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 25rpx;
    text-align: center;
    padding-top: 15rpx;
}

.t8 {
    display: flex;
    padding-bottom: 30rpx;
}

.t9 {
    margin-right: 34rpx;
    height: 50rpx;
    background-color: rgba(var(--red), var(--green), var(--blue), 0.15);
    text-align: center;
    line-height: 50rpx;
    padding: 5rpx 34rpx;
    border-radius: 100rpx;
    font-size: 26rpx;
    color: var(--Color);
    font-weight: 600;
}

.t10 {
    margin-right: 34rpx;
    height: 50rpx;
    background-color: rgba(var(--Gred), var(--Ggreen), var(--Gblue), 0.15);
    text-align: center;
    line-height: 50rpx;
    padding: 5rpx 34rpx;
    border-radius: 100rpx;
    font-size: 26rpx;
    color: var(--GColor);
    font-weight: 600;
}

.t111 {
    display: flex;
    padding: 0rpx 0rpx 0 30rpx;
    height: inherit;
    flex-direction: column;
    overflow: hidden;
}

.t11 {
    display: flex;
    width: 100%;
    flex-direction: column;
}
.t11:last-child {
    margin-bottom: 130rpx;
}
.t12 {
    display: flex;
    width: 100%;
}

.t13 {
    display: flex;
    margin-right: 30rpx;
}

.t14 {
    width: 120rpx;
    height: 120rpx;
    border-radius: 28rpx;
}

.t15 {
}

.t16 {
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 30rpx;
    font-weight: 600;
}

.t17 {
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 24rpx;
    color: gray;
    padding-top: 10rpx;
}

.t18 {
    display: flex;
    font-size: 24rpx;
    color: gray;
    align-items: center;
    padding-top: 10rpx;
}

.t19 {
}

.t20 {
    background: gray;
    width: 0;
    height: 22rpx;
    margin: 0 10rpx;
}

.t21 {
    word-break: keep-all;
    display: flex;
    align-items: center;
    margin-left: 30rpx;
    flex: 1;
    justify-content: flex-end;
}

.t22 {
    margin-right: 30rpx;
    height: 50rpx;
    background: rgba(var(--Gred), var(--Ggreen), var(--Gblue), 0.15);
    text-align: center;
    line-height: 50rpx;
    padding: 5rpx 35rpx;
    border-radius: 100rpx;
    font-size: 26rpx;
    color: var(--Color);
    font-weight: bold;
}

.line {
    width: auto;
    height: 2rpx;
    background: rgba(var(--Gred), var(--Ggreen), var(--Gblue), 0.25);
    margin: 30rpx 30rpx 30rpx 120rpx;
}

.scrollView {
    overflow: auto;
}

.topTag1 {
    font-size: 34rpx;
    font-weight: bold;
    color: var(--GColor);
}
.topTag2 {
    font-size: 34rpx;
    font-weight: bold;
    color: var(--Color);
}
</style>
